package lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Classname PrintBySynchronized
 * @Description TODO
 * @Date 2020/2/16 4:06 下午
 * @Created by gule
 */
public class PrintBySynchronized {
    private static Integer count = 0;
    private static boolean flag = true;
    private static Integer defaultValue = 200;
    private static Object lock = new Object();
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(()->{
            synchronized(lock) {
                while (count < defaultValue) {
                    if (flag) {
                        System.out.println("偶数 num is " + count);
                        count++;
                        flag = false;
                    }
                    lock.notifyAll();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        System.out.println("wait 异常");
                    }

                }
            }
        });
        executorService.execute(()->{
            synchronized(lock) {
                while (count < defaultValue) {
                    if (!flag) {
                        System.out.println("奇数 num is " + count);
                        count++;
                        flag = true;
                    }
                    lock.notifyAll();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        System.out.println("wait 异常");
                    }

                }
            }
        });
    }
}
